package cn.edu.nit.sys.handle;

import cn.edu.nit.sys.utils.JwtUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.util.Map;

/**
 * @Author 罗文斌
 * @Date 2023/4/13
 * @Version 1.0.0
 */
@ControllerAdvice
public class ResponseInterceptorHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        URI uri = request.getURI();
        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        HttpServletRequest servletRequest = req.getServletRequest();
        if(uri.getPath().indexOf("login") == -1 &&  !"app".equals(servletRequest.getHeader("OS"))
        && uri.getPath().indexOf("error") == -1 && uri.getPath().indexOf("code") == -1) {
            Map<String, Object> infoFromToken = JwtUtils.getInfoFromToken(servletRequest);
            ServletServerHttpResponse res = (ServletServerHttpResponse) response;
            HttpServletResponse servletResponse = res.getServletResponse();
            String username = infoFromToken.get("username").toString();
            servletResponse.addHeader("token", JwtUtils.generateToken(username, ""));
        }
        return body;
    }
}
